﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QuickDrawScreen
{
    public partial class DrawForm : Form
    {

        /// <summary>
        /// 蒙层
        /// </summary>
        Graphics mask;

        Boolean startDrawing = true;

        List<DrawAction> DrawQueue = new List<DrawAction>();

        List<DrawAction> DrawQueueReset = new List<DrawAction>();

        Boolean IsMouseLeftDown = false;

        Point LastPoint;

        public int CurDrawType = 1;


        public float PenSize = 3;

        public Color PenColor = Color.Red;

        /// <summary>
        /// 图片保存文件夹
        /// </summary>
        private String TempSaveFolder = "D:/QuickDrawScreenTemp/";

        public DrawForm()
        {
            InitializeComponent();
            // 最大化
            this.WindowState = FormWindowState.Maximized;
            // 不在任务栏显示
            this.ShowInTaskbar = true;
            //this.TopMost = true;

            // 无边框
            this.FormBorderStyle = FormBorderStyle.None;
        }

        private void DrawForm_Load(object sender, EventArgs e)
        {
            this.DoubleBuffered = true;
            CaptureScreen();
        }

        public void CaptureScreen()
        {
            // 获取屏幕
            Bitmap btp = GetScreenCapture();

            Image BackScreen = new Bitmap(btp, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

            // 在 BackScreen 上绘制蒙板
            mask = Graphics.FromImage(BackScreen);
            mask.FillRectangle(new SolidBrush(Color.FromArgb(0, 0, 0, 0)), 0, 0, BackScreen.Width, BackScreen.Height);
            this.BackgroundImage = BackScreen;


            this.Show();

        }

        /// <summary>
        /// 获取屏幕截图
        /// </summary>
        /// <returns></returns>
        private Bitmap GetScreenCapture()
        {
            Rectangle tScreenRect = new Rectangle(0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Bitmap tSrcBmp = new Bitmap(tScreenRect.Width, tScreenRect.Height); // 用于屏幕原始图片保存
            Graphics gp = Graphics.FromImage(tSrcBmp);
            gp.CopyFromScreen(0, 0, 0, 0, tScreenRect.Size);
            gp.DrawImage(tSrcBmp, 0, 0, tScreenRect, GraphicsUnit.Pixel);
            return tSrcBmp;
        }


        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            foreach (var item in DrawQueue)
            {
                if (item.ActType == (int)DrawTypeEnum.DrawLine || item.ActType == (int)DrawTypeEnum.MouserTrans)
                {
                    e.Graphics.DrawLine(item.Pen, item.StartPoint, item.EndPoint);

                }
                else if (item.ActType == (int)DrawTypeEnum.DrawRectangle)
                {
                    e.Graphics.DrawRectangle(item.Pen, item.StartPoint.X, item.StartPoint.Y, Math.Abs(item.EndPoint.X - item.StartPoint.X), Math.Abs(item.EndPoint.Y - item.StartPoint.Y));
                }
                else
                {
                    //Font f = new Font("Verdana", 32);
                    //Brush b = new SolidBrush(Color.White);
                    //string addText = "我爱你中国";
                    //mask.DrawString(addText, f, b, 10, 10);
                    //mask.Dispose();

                }
            }
        }

        private void DrawForm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //不要给窗口设置菜单，不然右键也有效
                contextMenuStrip1.Show(e.X + this.Left, e.Y + this.Top);
                return;
            }

            //if (!startDrawing)
            //{
            //    return;
            //}
            if (e.Button == MouseButtons.Left)
            {
                this.IsMouseLeftDown = true;
                LastPoint = new Point(e.X, e.Y);

                if (CurDrawType == (int)DrawTypeEnum.DrawLine)
                {
                    //先画个点
                    DrawQueue.Add(new DrawAction(new Pen(PenColor, PenSize)) { ActType = (int)DrawTypeEnum.DrawLine, StartPoint = LastPoint, EndPoint = LastPoint });
                }
                else if (CurDrawType == (int)DrawTypeEnum.MouserTrans)
                {
                    //先画个点
                    DrawQueue.Add(new DrawAction(new Pen(PenColor, PenSize)) { ActType = (int)DrawTypeEnum.MouserTrans, StartPoint = LastPoint, EndPoint = LastPoint });
                }
                else if (CurDrawType == (int)DrawTypeEnum.DrawRectangle)
                {
                    //先画个点
                    DrawQueue.Add(new DrawAction(new Pen(PenColor, PenSize)) { ActType = (int)DrawTypeEnum.DrawRectangle, StartPoint = LastPoint, EndPoint = LastPoint });
                }
            }
        }

        private void DrawForm_MouseUp(object sender, MouseEventArgs e)
        {
            //左键up才是画图结束
            if (e.Button == MouseButtons.Left)
            {
                IsMouseLeftDown = false;
                DrawQueue.Add(new DrawAction() { ActType = (int)DrawTypeEnum.ActEnd });
            }
            else
            {
                //可能是其它
            }


        }


        private void DrawForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (!startDrawing)
            {
                return;
            }

            if (!IsMouseLeftDown)
            {
                return;
            }

            if (CurDrawType == (int)DrawTypeEnum.DrawLine)
            {
                DrawQueue[DrawQueue.Count - 1].EndPoint.X = e.X;
                DrawQueue[DrawQueue.Count - 1].EndPoint.Y = e.Y;
                Refresh();
            }

            if (CurDrawType == (int)DrawTypeEnum.DrawRectangle)
            {
                DrawQueue[DrawQueue.Count - 1].EndPoint.X = e.X;
                DrawQueue[DrawQueue.Count - 1].EndPoint.Y = e.Y;
                Refresh();
            }

            if (CurDrawType == (int)DrawTypeEnum.MouserTrans)
            {

                var act = new DrawAction(new Pen(PenColor, PenSize)) { ActType = (int)DrawTypeEnum.MouserTrans };

                act.StartPoint.X = LastPoint.X;
                act.StartPoint.Y = LastPoint.Y;

                act.EndPoint.X = e.X;
                act.EndPoint.Y = e.Y;

                LastPoint.X = e.X;
                LastPoint.Y = e.Y;
                DrawQueue.Add(act);

                Refresh();
            }
        }

        public void BackToMainForm()
        {
            startDrawing = false;
            IsMouseLeftDown = false;
            mask.Clear(Color.FromArgb(0, 0, 0, 0));
            mask = null;
            this.Hide();

            MainForm.MainFormInstance.Show();
        }

        private void DrawForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Z && e.Control)
            {
                Return();
            }

            if (e.KeyData == Keys.Escape)
            {
                BackToMainForm();
            }


        }


        public void Return()
        {

            var lastSearchActTypeEndNum = 0;
            var lastSearchActTypeEndNumIndex = -1;
            for (int i = DrawQueue.Count - 1; i >= 0; i--)
            {
                if (DrawQueue[i].ActType == (int)DrawTypeEnum.ActEnd)
                {
                    lastSearchActTypeEndNum++;
                }

                if (lastSearchActTypeEndNum == 2)
                {
                    lastSearchActTypeEndNumIndex = i;
                    break;
                }
                DrawQueue[i].itemTo = 1;
            }

            //如果只能找到一个  说明只有一步
            if (lastSearchActTypeEndNumIndex == -1)
            {
                DrawQueueReset.AddRange(DrawQueue);
                DrawQueue.Clear();
            }
            else
            {

                DrawQueueReset.AddRange(DrawQueue.TakeWhile(x => x.itemTo == 1).ToList());
                DrawQueue.RemoveRange(lastSearchActTypeEndNumIndex + 1, DrawQueue.Count - lastSearchActTypeEndNumIndex - 1);
            }

            Refresh();

        }

        private void mouseTransMenuItem_Click(object sender, EventArgs e)
        {
            startDrawing = true;
            this.CurDrawType = (int)DrawTypeEnum.MouserTrans;
        }

        private void lineMenuItem_Click(object sender, EventArgs e)
        {
            startDrawing = true;
            this.CurDrawType = (int)DrawTypeEnum.DrawLine;
        }

        private void RectangleMenuItem_Click(object sender, EventArgs e)
        {
            startDrawing = true;
            this.CurDrawType = (int)DrawTypeEnum.DrawRectangle;
        }

        private void clearMenuItem_Click(object sender, EventArgs e)
        {
            DrawQueue.Clear();
            startDrawing = false;
            Refresh();
            startDrawing = true;

        }

        private void QuitMenuItem_Click(object sender, EventArgs e)
        {
            BackToMainForm();
        }

        private void returnMenuItem_Click(object sender, EventArgs e)
        {
            Return();
        }



        #region 颜色

        private void penColorOrangeRedMenuItem_Click(object sender, EventArgs e)
        {
            PenColor = Color.OrangeRed;
        }

        private void penColorBlueMenuItem_Click(object sender, EventArgs e)
        {
            PenColor = Color.DeepSkyBlue;
        }

        private void penColorGreenMenuItem_Click(object sender, EventArgs e)
        {
            PenColor = Color.LimeGreen;
        }

        #endregion

        #region 笔画粗细

        private void penSizeMinMenuItem_Click(object sender, EventArgs e)
        {
            PenSize = 2;
        }

        private void penSizeMidMenuItem_Click(object sender, EventArgs e)
        {
            PenSize = 4;
        }

        private void pensizeLargeMenuItem_Click(object sender, EventArgs e)
        {
            PenSize = 6;
        }
        #endregion

        private void savePicMenuItem_Click(object sender, EventArgs e)
        {
            Bitmap bitmap = GetScreenCapture();
            if (Directory.Exists(TempSaveFolder) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(TempSaveFolder);
            }
            bitmap.Save(TempSaveFolder + DateTime.Now.ToString("yyMMddHHmmss") + ".png");
        }
    }
}
